﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Google.Apis.Calendar.v3;
using Google.Apis.Calendar.v3.Data;
using System.Windows;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Util.Store;
using System.Threading.Tasks;

namespace CalendarScreenSaver
{
    public class GoogleCalendarManager
    {
        const string _clientId = "<Calendar ID>";
        const string _clientSecret = "<Google API Key>";
        public GoogleCalendarManager()
        {
        }

        public async Task<List<Event>> GetMyEventsAsync(Settings settings)
        {
            UserCredential credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                new ClientSecrets { ClientId = _clientId, ClientSecret = _clientSecret },
                new[] { Uri.EscapeUriString(CalendarService.Scope.Calendar) },
                settings.UserName,
                System.Threading.CancellationToken.None,
                new FileDataStore("MyCalendar"));

            var service = new CalendarService(new Google.Apis.Services.BaseClientService.Initializer
            {
                HttpClientInitializer = credential,
                ApplicationName = "Screensaver Calendar v1"
            });

            var result = service.CalendarList.List().Execute();
            var calendar = (from c in result.Items
                       where c.Summary.ToLower() == settings.CalendarName.Trim().ToLower()
                       select c).FirstOrDefault();

            if (calendar != null)
            {                
                var events = service.Events.List(calendar.Id);

                events.TimeMin = DateTime.Now.StartOfWeek(DayOfWeek.Monday);
                events.TimeMax = DateTime.Now.StartOfWeek(DayOfWeek.Monday).AddDays(7).AddSeconds(-1);
                var items = events.Execute().Items;

                return new List<Event>(items);
            }

            return null;
        }
    }

    public static class DateTimeExtensions
    {
        public static DateTime StartOfWeek(this DateTime dt, DayOfWeek startOfWeek)
        {
            int diff = dt.DayOfWeek - startOfWeek;
            if (diff < 0)
            {
                diff += 7;
            }

            return dt.AddDays(-1 * diff).Date;
        }
    }
}
